<template>
  <div>
    <Card>
      <div class="flexCSB">
        <Button type="primary" @click="getAdd">新增用户</Button>
        <div style="display: flex">
          <Input
            style="width: 300px;margin-right: 10px"
            placeholder="请输入用户名"
            suffix="ios-search"
            v-model="username"
            @on-change="getMembers"
          ></Input>
          <Input
            style="width: 300px;"
            placeholder="请输入用户手机号"
            suffix="ios-search"
            v-model="phone"
            @on-change="getMembers"
          ></Input>
        </div>
      </div>
      <Table
        class="table"
        :loading="loading"
        highlight-row
        :columns="columns"
        :data="data"
      ></Table>
      <Page
        show-total
        class="page"
        :total="total"
        :current.sync="current"
        show-elevator
        @on-change="changePage"
      />
    </Card>
    <Modal
      v-model="userModal"
      :title="modelTitle"
      width="35"
      :closable="false"
      :mask-closable="true"
    >
      <Form ref="form" :model="userInfo" :rules="rules" :label-width="90">
        <FormItem label="用户名：" prop="username">
          <Input
            v-model="userInfo.username"
            placeholder="请输入用户名"
            :style="{ width: '300px' }"
          ></Input>
        </FormItem>
        <FormItem label="密码：" prop="password" v-if="isADD">
          <Input
            v-model="userInfo.password"
            placeholder="请输入密码"
            :style="{ width: '300px' }"
          ></Input>
        </FormItem>
        <FormItem label="手机号：" prop="phone">
          <Input
            v-model="userInfo.phone"
            type="number"
            placeholder="请输入手机号"
            :style="{ width: '300px' }"
          ></Input>
        </FormItem>
        <FormItem label="邮箱：" prop="email">
          <Input
            v-model="userInfo.email"
            placeholder="请输入邮箱"
            :style="{ width: '300px' }"
          ></Input>
        </FormItem>

        <Form-item label="组织机构" prop="organizationId">
          <Select
            v-model="userInfo.organizationId"
            :style="{ width: '300px' }"
            placeholder="请选择组织机构"
            @on-change="changeOrg"
          >
            <Option
              v-for="(item, index) in orgList"
              :key="index"
              :value="item.id"
            >
              {{ item.name }}
            </Option>
          </Select>
        </Form-item>
        <Form-item label="角色" prop="roleId">
          <Select
            v-model="userInfo.roleId"
            :style="{ width: '300px' }"
            placeholder="请选择角色"
          >
            <Option
              v-for="(item, index) in roleList"
              :key="index"
              :value="item.id"
            >
              {{ item.name }}
            </Option>
          </Select>
        </Form-item>
        <Form-item style="text-align: right">
          <Button type="primary" @click="handleSubmit('form')">提交</Button>
          <Button @click="handleReset('form')" style="margin-left: 8px"
            >取消</Button
          >
        </Form-item>
      </Form>
      <div slot="footer">
        <!-- <Button class="Button" type="primary" @click="submit">确认登陆</Button> -->
      </div>
    </Modal>
    <Modal title="重置密码" v-model="restModal" width="40">
      <Form ref="form1" :model="psw" :rules="restRules" :label-width="100">
        <FormItem label="新密码" prop="password">
          <Input
            v-model="psw.password"
            :style="{ width: '300px' }"
            placeholder="请输入新密码"
          ></Input>
        </FormItem>
        <Form-item style="text-align: right">
          <Button type="primary" @click="handleSubmit1('form1')">提交</Button>
          <Button @click="handleReset1('form1')" style="margin-left: 8px"
            >取消</Button
          >
        </Form-item>
      </Form>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import { md5 } from "../../config/md5";
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    return {
      loading: false,
      columns: [
        { title: "用户名", key: "username", align: "center", minWidth: 150 },
        { title: "邮箱", key: "email", align: "center", minWidth: 150 },
        { title: "手机号", key: "phone", align: "center", minWidth: 150 },
        { title: "角色名称", key: "roleName", align: "center", minWidth: 100 },
        {
          title: "组织名称",
          key: "organizationName",
          align: "center",
          minWidth: 150,
        },
        { title: "添加时间", key: "gmtCreate", align: "center", minWidth: 200 },
        {
          title: "状态",
          align: "center",
          minWidth: 150,
          render: (h, params) => {
            if (params.row.states == 1) {
              return h(
                "Tag",
                {
                  props: { color: "green" },
                },
                "启用"
              );
            } else {
              return h(
                "Tag",
                {
                  props: { color: "red" },
                },
                "禁用"
              );
            }
          },
        },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          width: 380,
          render: (h, params) => {
            let contentB = "";
            let typeB = "";
            if (params.row.states == 1) {
              contentB = "禁用";
              typeB = "warning";
            } else {
              contentB = "启用";
              typeB = "success";
            }
            return h("div", [
              h(
                "Button",
                {
                  props: { type: "info" },
                  style: {
                    // "margin-left": "10px",
                  },
                  on: {
                    click: () => {
                      this.openPop(params.row);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: { type: typeB },
                  style: {
                    "margin-left": "10px",
                  },
                  on: {
                    click: () => {
                      this.getUserState(params.row);
                    },
                  },
                },
                contentB
              ),
              h(
                "Button",
                {
                  props: { type: "success" },
                  style: {
                    "margin-left": "10px",
                  },
                  on: {
                    click: () => {
                      this.getOpenRest(params.row);
                    },
                  },
                },
                "重置密码"
              ),
              h(
                "Button",
                {
                  props: { type: "error" },
                  style: {
                    "margin-left": "10px",
                  },
                  on: {
                    click: () => {
                      this.del(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      data: [],
      total: 0,
      current: 1,
      size: 10,
      username: "",
      id:'',
      phone: "",
      userModal: false,
      userInfo: {
        username: "",
        password: "",
        email: "",
        roleId: "",
        organizationId: "1",
        phone: "",
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        phone: [{ validator: validatePhone, required: true, trigger: "blur" }],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        organizationId: [
          { required: true, message: "请选择组织机构", trigger: "change" },
        ],
      },

      modelTitle: "新增用户",
      roleList: [],
      orgList: [],
      orgId: "",
      isADD: true, //新增、修改
      restModal: false,
      psw: {
        password: "",
      },
      restRules: {
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
      accountId: "",
    };
  },
  created() {
    this.getMembers();
    // this.getGroup();
  },
  methods: {
    // 获取列表
    getMembers() {
      this.loading = true;
      this.$http(
        "/chongqing/stage/role/getRoleList",
        {
          current: this.current, // 第几页
          size: this.size, // 每页数据大小
          username: this.username,
          phone: this.phone
        },
        "post",
        (res) => {
          if (res.data.code == 1000) {
            this.data = res.data.data.records;
            this.total = res.data.data.total;
          } else {
            this.$Message.error(res.data.msg);
          }
          this.loading = false;
        }
      );
    },
    // 改变组织机构的选择
    changeOrg(data) {
      console.log(data);
      this.getRoleList(data);
    },
    // 获取角色列表，角色选择器
    getRoleList(id) {
      this.$http(
        "/chongqing/stage/role/getRoleOption",
        {
          orgId: id,
        },
        "get",
        (res) => {
          if (res.data.code == 1000) {
            console.log(res.data.data);
            this.roleList = res.data.data;
          } else {
            this.$Message.error(res.data.msg);
          }
        }
      );
    },
    del(row){
      this.$confirm('此操作将删除该用户，请谨慎操作，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showClose: false,
          type: 'warning'
        }).then(() => {
          this.$http('/chongqing/stage/account/deleteAccount', {
            accountId: row.id
          }, 'post', (res) => {
            if (res.data.code == 1000 && res.data.data) {
              this.$Message.success('删除成功')
              this.current = 1
              this.getMembers()
              // this.getBottomExhibitionHallDropDown()
            } else {
              this.$Message.error(res.data.msg)
            }
            // this.modal = false
          })
        }).catch(() => {

        })
    },
    // 获取组织机构列表，组织机构选择器
    getGroup() {
      this.$http("/chongqing/stage/group/selector", {}, "get", (res) => {
        if (res.data.code == 1000) {
          this.orgList = res.data.data;
        } else {
          this.$Message.error(res.data.msg);
        }
      });
    },
    // 切换页码
    changePage(data) {
      this.current = data;
      this.getMembers();
    },
    // 打开修改弹窗
    async openPop(row) {
      console.log(row);
      this.isADD = false;
      this.modelTitle = "修改用户";
      await this.getGroup(); // 获取组织机构数据
      await this.getRoleList(row.organizationId);
      this.userInfo = {
        username: row.username,
        email: row.email,
        roleId: row.roleId,
        organizationId: row.organizationId,
        phone: row.phone,
      };
      this.id=row.id
      this.userModal = true;
    },

    handleSubmit(form) {
      // this.isCustom = true;
      let that = this;
      this.$refs[form].validate((valid) => {
        if (valid) {
          // this.$Message.success("提交成功!");
          if (this.modelTitle == "新增用户") {
            this.$http(
              "/chongqing/stage/account/addAccount",
              {
                email: this.userInfo.email,
                organizationId: this.userInfo.organizationId,
                password: md5(this.userInfo.password),
                phone: this.userInfo.phone,
                roleId: this.userInfo.roleId,
                username: this.userInfo.username,
              },
              "post",
              (res) => {
                if (res.data.code == 1000) {
                  that.current = 1;
                  that.getMembers();
                  that.$Message.success(res.data.msg);
                  that.$refs[form].resetFields();
                  that.userModal = false;
                } else {
                  this.$Message.error(res.data.msg);
                }
              }
            );
          } else {
            console.log(333);
            this.$http('/chongqing/stage/account/updateAccount',{
              email:this.userInfo.email,
              id:this.id,
              organizationId:this.userInfo.organizationId,
              phone:this.userInfo.phone,
              roleId:this.userInfo.roleId,
              username:this.userInfo.username
            },'post',(res)=>{
              if(res.data.code==1000){
                 that.current = 1;
                  that.getMembers();
                  that.$Message.success(res.data.msg);
                  that.$refs[form].resetFields();
                  that.userModal = false;
              }else{
                this.$Message.error(res.data.msg);
              }
            })
          }
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    },
    // 取消表单，关闭modal
    handleReset(form) {
      this.userModal = false;
      this.$refs[form].resetFields();
    },
    getAdd() {
      this.modelTitle = "新增用户";
      this.id='',
      this.isADD = true;
      this.getGroup();
      this.userModal = true;
    },
    // 更改用户状态
    getUserState(row) {
      if (row.states == 1) {
        this.getDisableUser(row.id);
      } else {
        this.getEnableUser(row.id);
      }
    },
    // 禁用
    getDisableUser(data) {
      console.log(data);
      this.$confirm("此操作将禁用该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http(
            "/chongqing/stage/account/disableAccount",
            {
              accountId: data,
            },
            "post",
            (res) => {
              console.log(res);
              if (res.data.data.flag == true) {
                this.$message({
                  type: "success",
                  message: "禁用成功!",
                });
                this.current = 1;
                this.getMembers();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 启用
    getEnableUser(data) {
      console.log(data);
      this.$confirm("此操作将启用该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http(
            "/chongqing/stage/account/enableAccount",
            {
              accountId: data,
            },
            "post",
            (res) => {
              console.log(res);
              if (res.data.data.flag == true) {
                this.$message({
                  type: "success",
                  message: "禁用成功!",
                });
                this.current = 1;
                this.getMembers();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 重置密码
    getOpenRest(row) {
      this.accountId = row.id;
      this.restModal = true;
    },
    // 退款提交
    handleSubmit1(form1) {
      let that = this;
      this.$refs[form1].validate((valid) => {
        if (valid) {
          this.$http(
            "/chongqing/stage/account/restPassword",
            {
              password: md5(this.psw.password),
              accountId: this.accountId,
            },
            "post",
            (res) => {
              console.log(res);
              console.log(res.data.data);
              if (res.data.code == 1000) {
                that.restModal = false;
                that.$Message.success(res.data.msg);
                that.$refs[form1].resetFields();
              } else {
                that.$Message.error(res.data.msg);
              }
            }
          );
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    },
    handleReset1(form1) {
      this.restModal = false;
      this.$refs[form1].resetFields();
    },
  },
};
</script>

<style scoped>
.test {
  cursor: pointer;
}
</style>
